﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SharedLib.MessageFramework
{
    public abstract class AppMessage : IAppMessage 
    {
        object _sender;
        object _data;
        object _result;
        MessageCallback _callback;
        Exception _exception;

        public abstract Type Handler
        {
            get;
        }

        public virtual string HandlerUID
        {
            get
            {
                return Handler.Name;
            }
        }

        public object Data
        {
            get { return _data; }
        }
        public object Sender
        {
            get { return _sender; }
        }
        public object Result
        {
            get { return _result; }
            set { _result = value; }
        }
        public MessageCallback CallBack
        {
            get { return _callback; }
        }

        public Exception Exception
        {
            get { return _exception; }
            set { _exception = value; }
        }

        public AppMessage(object sender, object data, MessageCallback callback)
        {
            _sender = sender;
            _data = data;
            _callback = callback;
        }

        private long _cancelFlag = 0;
        /// <summary>
        /// Thread-safe on-off switch flag
        /// </summary>
        public bool CancelFlag
        {
            get
            {
                return (Interlocked.Read(ref _cancelFlag) == 1);
            }
            set
            {
                if (value)
                {
                    Interlocked.Exchange(ref _cancelFlag, 1);
                }
                else
                {
                    Interlocked.Exchange(ref _cancelFlag, 0);
                }
            }
        }
    }
}
